package com.biqee.service.tb.impl;

import java.io.FileInputStream;
import java.io.InputStream;

import net.sf.json.JSONObject;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.model.db.TbItem;
import com.biqee.service.tb.TbItemParseService;
import com.biqee.util.JsoupUtil;
import com.biqee.util.UrlUtil;

public class TbItemParseServiceImpl implements TbItemParseService {
	private static final Logger logger = Logger.getLogger(TbItemParseServiceImpl.class);
	
	@Override
	public TbItem parse(InputStream inputStream, String charsetName, String pageUrl) {
		Document doc = JsoupUtil.createDocument(inputStream, charsetName, pageUrl);
		if(doc == null) {
			logger.error("create doc failed. charsetName: " + charsetName + ", url: " + pageUrl);
			return null;
		}
		
		return parseItem(doc);
	}	

	@Override
	public TbItem parse(String htmlStr) {
		Document doc = JsoupUtil.createDocument(htmlStr);
		if(doc == null) {
			if(logger.isDebugEnabled()) {
				logger.debug("create doc failed. htmStr: " + htmlStr);
			} else {
				logger.error("create doc failed");				
			}
			return null;
		}
		
		return parseItem(doc);
	}

	private void setShopInfo(Document doc, TbItem tbItem) {
		boolean isShopUrlFound = false;
		boolean isShopIdFound = false;
		Elements divElements = doc.select("div");
		for(Element divElement : divElements) {
			String divClass = divElement.attr("class");
			if("shop-info-simple".equalsIgnoreCase(divClass) || "tb-shop-info-simple".equalsIgnoreCase(divClass)) {
				Element aHrefElement = divElement.select("a").first();
				String href = aHrefElement.attr("href");
				if(href.endsWith(".taobao.com")) {
					isShopUrlFound = true;
					tbItem.setTbShopUrl(href);
				}
			}
			
			if("shop-other".equalsIgnoreCase(divClass) || "tb-shop-other".equalsIgnoreCase(divClass)) {
				Elements aHrefElements = divElement.select("a");
				for(Element aHrefElement : aHrefElements) {
					String aHrefClass = aHrefElement.attr("class");
					if("tb-feed subscribe-rss".equals(aHrefClass)) {
						String href = aHrefElement.attr("href");
						String shopId = UrlUtil.getParam(href, "shopId");
						if(shopId != null) {
							isShopIdFound = true;
							tbItem.setTbShopId(shopId);
						}
					}
				}
			}
		}
		
		if(!isShopUrlFound || !isShopIdFound) {
			Elements formElements = doc.select("form");
			Element searchForm = null;
			for(Element formElement : formElements) {
				if("SearchForm".equals(formElement.attr("name"))) {
					searchForm = formElement;
					break;
				}	
			}
			if(searchForm != null) {
				String tbShopUrl = searchForm.attr("action");
				isShopUrlFound = true;
				tbItem.setTbShopUrl(tbShopUrl);
				
				Elements inputElements = searchForm.select("input");
				for(Element inputElement : inputElements) {
					String name = inputElement.attr("name");
					if("shopId".equals(name)) {
						isShopIdFound = true;
						tbItem.setTbShopId(inputElement.attr("value"));
					}
				}				
			}
		}

		if(!isShopUrlFound || !isShopIdFound) {
			// <div id="LineZing" pagetype="2" shopid="58811884" tmplid="" itemid="3312990997"></div></body>
			for(Element divElement : divElements) {
				String id = divElement.attr("id");
				if("LineZing".equalsIgnoreCase(id)) {
					String shopId = divElement.attr("shopid");
					isShopIdFound = true;
					tbItem.setTbShopId(shopId);
					isShopUrlFound = true;
					tbItem.setTbShopUrl("http://store.taobao.com/?shop_id=" + shopId);
				}
			}
		}
		
		if(!isShopUrlFound || !isShopIdFound) {
			// <div id="rr-detail-recommend" data-sellerid="40694262"
			for(Element divElement : divElements) {
				String id = divElement.attr("id");
				if("rr-detail-recommend".equalsIgnoreCase(id)) {
					String sellerId = divElement.attr("data-sellerid");
					isShopUrlFound = true;
					tbItem.setTbShopUrl("http://store.taobao.com/shop/view_shop.htm?user_number_id=" + sellerId);
					isShopIdFound = true;
					tbItem.setTbShopId(TbItem.UNKNOWN_SHOP_ID);
				}
			}
		}
		
		if(!isShopUrlFound) {
			throw new RuntimeException("shop url not found ");
		}
		
		if(!isShopIdFound) {
			throw new RuntimeException("shop id not found ");
		}
	}
	
	private TbItem parseItem(Document doc) {
//		Element lpTokenElement = doc.select("div.tb-lp-header-top").first();
//		if(lpTokenElement != null) {
//			logger.warn("skip wumingliangpin store!");
//			return null;
//		}
		
		try {
			TbItem tbItem = new TbItem();
			
			Elements divElements = doc.select("div");
			for(Element divElement : divElements) {
				String id = divElement.attr("id");
				if("rr-detail-recommend".equals(id)) {
					tbItem.setSellerId(divElement.attr("data-sellerid"));
					tbItem.setTbCatId(divElement.attr("data-catid"));
				}
				
				if("J_itemViewed".equals(id)) {
					String value = divElement.attr("data-value");
					try {
						JSONObject jsonObject = JSONObject.fromObject(value); 
						String itemId = jsonObject.getString("itemId");
						tbItem.setTbItemId(itemId);
						
						String pic = jsonObject.getString("pic");
						tbItem.setDetailLogo(pic);		
					} catch (Exception ex) {
						logger.error("failed in parsing json str: " + value);
						throw ex;
					}
				}
			}
			
			setShopInfo(doc, tbItem);
			
			Elements formElements = doc.select("form");
			Element bidElement = null;
			for(Element e : formElements) {
				if("J_FrmBid".equals(e.attr("id"))) {
					bidElement = e;
					break;
				}	
			}
			Elements inputElements = bidElement.select("input");
			for(Element inputElement : inputElements) {
				String name = inputElement.attr("name");
				
				if("title".equals(name)) {
					tbItem.setTitle(inputElement.attr("value"));
				}
				
				if("seller_nickname".equals(name)) {
					tbItem.setSellerNick(inputElement.attr("value"));
				}
				
				if("region".equals(name)) {
					tbItem.setPlace(inputElement.attr("value"));
				}
				
				if("current_price".equals(name)) {
					tbItem.setMinPrice(Double.parseDouble(inputElement.attr("value")));
					tbItem.setMaxPrice(Double.parseDouble(inputElement.attr("value")));
				}
			}
			
			// 价格区间没得取
			// 商家促促销价格没得取
			
			Elements liElements = doc.select("li");
			for(Element liElement : liElements) {
				String liClassStr = liElement.attr("class");
				if(liClassStr.startsWith("tb-sold-out")) {
					Element emElement = liElement.select("em").first();
					tbItem.setSales(Integer.parseInt(emElement.text()));
				}
			}
			
			return tbItem;
		} catch (Exception e) {
			logger.error("parse doc failed. doc: " + doc.baseUri() +
					", cause: ", e);
		}
		
		return null;
	}
	
	public static void main(String[] args) {
		String filePath = "D:\\work\\biqee\\test-pages\\taobao\\common\\wmlp2.html";
			//	"D:\\work\\biqee\\test-pages\\taobao\\common\\common-item.html";
		InputStream in;
		TbItem result = null;
		try {
			in = new FileInputStream(filePath);
			TbItemParseServiceImpl parser = new TbItemParseServiceImpl();
			result = parser.parse(in, "gbk", "http://item.taobao.com/item.htm?id=8211370550");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String desc = ToStringBuilder.reflectionToString(result, ToStringStyle.MULTI_LINE_STYLE);
		System.out.println(desc);
	}

}